<template>
  <tiny-select
      render-type="tree"
      v-model="model"
      :size="props.size"
      :value-field="valueKey"
      :text-field="labelKey"
      :tree-op="treeOp"
      :clearable="clearable"
      :placeholder="placeholder"
      @change="change"
  />
</template>

<script setup>
import tool from '@/utils/tool'
import {ref, onBeforeMount,watch} from 'vue'
import {TinySelect} from "@opentiny/vue";
const props = defineProps({
  text: { type: [String, Number], default: '' },
  sql: { type: String, default: '' },
  size: { type: String, default: 'small' },
  valueKey: { type: String, default: 'id' },
  labelKey: { type: String, default: 'name' },
  height: { type: [String, Number], default: '' },
  disabled: { type: Boolean, default: false },
  clearable: { type: Boolean, default: true },
  list: { type: [String, Array], default: '' },
  readonly: { type: Boolean, default: false }, // 必填
  required: { type: Boolean, default: false }, // 必填
  border: { type: Boolean, default: true }, // 禁用
  placeholder: { type: String, default: '' }, // 自定义样式
  borderColor: { type: String, default: '' }, // 边框色
  bgColor: { type: String, default: '' }, // 背景色
  listWidth: { type: Number, default: 0 }, // 下拉框宽度
  cat: { type: String, default: '' }, // 取数据cat分类
  options: {
    type: Array,
    default: () => {
      return []
    }
  } // 如果传入值
})
const emit = defineEmits(['Esc', 'enter', 'change'])
const model = defineModel()
const name = defineModel('name')
const code = defineModel('code')

onBeforeMount(() => {
  getList()
})
const treeOp = ref({data: []})
const getList = () => {
  tool.post('common/dropdown', { cat: props.cat, keyWord: '' }).then((ret) => {
    if (ret.stat) {
      treeOp.value.data = ret.data
    }
  })
}
const change = (item) => {
  if(item) {
    code.value = item.code ? item.code : ''
    name.value = item[props.labelKey] ?item[props.labelKey] :''
  }
  else {
    code.value = ''
    name.value = ''
  }
  setTimeout(()=>{
    emit('change', item?{ id: item[props.valueKey], name: item[props.labelKey] }:null)
  },1)
}

</script>

<style scoped lang="scss">

</style>